package com.gxa.realm;

import com.gxa.entity.SysMenu;
import com.gxa.entity.SysRole;
import com.gxa.entity.SysUser;
import com.gxa.mapper.SysMenuMapper;
import com.gxa.mapper.SysRoleMapper;
import com.gxa.mapper.SysUserMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class MyRealm extends AuthorizingRealm {
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SysRoleMapper sysRoleMapper;
    @Autowired
    SysMenuMapper sysMenuMapper;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权");
        String username =(String) principalCollection.getPrimaryPrincipal();
        SysUser select = sysUserMapper.select(username);
        Integer id = select.getId();
        List<SysRole> sysRoleByUserId = sysRoleMapper.findSysRoleByUserId(id);
        if (sysRoleByUserId.size()>0){

            Set<String> set = new HashSet<>();
            List<Integer> list = new ArrayList<>();
            for (SysRole name:sysRoleByUserId){
                set.add(name.getTitle());
                int id1=(int)name.getId();
                list.add(id);
            }
            List<SysMenu> select1 = sysMenuMapper.select(list);
            Set<String> set1 = new HashSet<>();
            for (SysMenu sysMenu:select1){
                set1.add(sysMenu.getTitle());
            }
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            System.out.println(set);
            info.setRoles(set);
            info.setStringPermissions(set1);
            System.out.println(set1);
           return info;
        }

        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证");
        String username =  authenticationToken.getPrincipal().toString();
        SysUser select = sysUserMapper.select(username);
        if(select != null){
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(select.getUerName(),select.getPassWord(),"myRealm");
            //加盐
            info.setCredentialsSalt(ByteSource.Util.bytes(select.getSalt()));

            return info;
        }
        return null;
    }
}
